import { Form, Input } from 'antd-mobile'
import styles from './index.module.less'
import { useEffect, useRef } from 'react'
import { useState } from 'react'
import FormPicker from '@/components/FormComponets/FormPicker'
import { AddCircleOutline } from 'antd-mobile-icons'
import arrow_down from '@/resource/arrow_down.png'
import { observer, useLocalObservable } from 'mobx-react'
import Store from '../store'
import BtnBotLayout from '@/components/BtnBotLayout'
import CustomSlider from '../components/Slider'
import { history, useParams } from 'umi'
import { toJS } from 'mobx'
import { scrollToById } from '@/utils'
import GenerateRainbow from '@/components/GenerateRainbow'

const maxAge = 100

/** 默认初始年龄列表 */
let ageArr: any[] = []
for (let i = 0; i <= maxAge; i++) {
    ageArr.push({ label: `${i}岁`, value: `${i}` })
}

/** 默认角色名称 */
// const roleNameList = ['子女', '学生', '休闲者', '公民', '工作者', '持家者']

/** 获取剩下的年龄段 */
function getRestAge(arr: { lable: string; value: string }[], excludedRanges: any[][]) {
    const result = arr.filter(i => {
        // 遍历数组，排除指定区间
        for (const [start, end] of excludedRanges) {
            if (Number(i.value) >= Number(start) && Number(i.value) <= Number(end)) {
                return false
            }
        }
        return true
    })
    return result
}

export default observer(() => {
    const store = useLocalObservable(() => Store())
    const { stepData, submit } = store
    const generateRef = useRef<any>()
    const [form] = Form.useForm()
    const [errInfo, setErrorInfo] = useState<any>({}) /** 错误下标 */
    const { id } = useParams<any>()

    const handleSubmit = () => {
        return form
            .validateFields()
            .then((values: any) => {
                setErrorInfo({})
                submit(values, generateRef)
            })
            .catch(err => {
                /** 错误提示 */
                const { errorFields = [] } = err || {}
                let errIndex: any = {}
                errorFields.forEach((item: any, idx: number) => {
                    const { name, errors } = item
                    if (errors.length) {
                        errIndex[`${name['1']}_${name['3']}`] = 1
                    }
                    if (idx === 0) {
                        scrollToById(document.getElementsByClassName('content_wrappper')[0] as HTMLElement, `data_${name['1']}_${name['3']}`)
                    }
                })
                setErrorInfo(errIndex)
            })
    }

    /** 刷新字段 */
    function handleValuesChange(_changedFields: any, allFields: any) {
        console.log('刷新字段', _changedFields, allFields)
        // form.setFieldsValue(allFields)
    }

    useEffect(() => {
        if (stepData.length === 0) {
            history.replace(`/rainbow/step1/${id}?id=${id}`)
        } else {
            form.setFieldsValue({
                data: toJS(stepData),
            })
        }
        document.title = '生涯彩虹图'
    }, [stepData])

    return (
        <div className={styles.outside}>
            <BtnBotLayout
                footer={
                    <div className={styles.options}>
                        <div
                            className={styles.white_btn}
                            onClick={() => {
                                history.replace(`/rainbow/step1/${id}?from=step2&id=${id}`)
                            }}
                        >
                            上一步
                        </div>
                        <div className={styles.blue_btn} onClick={handleSubmit}>
                            生成彩虹图
                        </div>
                    </div>
                }
            >
                <div className={styles.step_tips}>
                    请根据自己设置的角色和其对应的开始和结束时间的广度，深度思考每个角色你会投入的程度。新建年龄段（例如孩子0-3岁，5分），可选0-5分，0分代表没有色块，5分代表色块最高， 完成生成彩虹图
                </div>
                <div className={styles.container}>
                    <Form form={form} layout="horizontal" onValuesChange={handleValuesChange}>
                        <Form.Array name="data">
                            {dataItem =>
                                dataItem.map(({ index: dataIdx }, i) => (
                                    <>
                                        {i === 0 && (
                                            <div className={styles.title}>
                                                <span className={styles.title_span}>第二步：程度设置</span>
                                            </div>
                                        )}
                                        <div className={styles.role_block}>
                                            <div className={styles.block_title}>
                                                <span>
                                                    角色{dataIdx + 1}：{stepData[dataIdx]?.name}
                                                </span>
                                                <span>
                                                    时间广度：{stepData[dataIdx]?.age_start?.[0]}岁~
                                                    {stepData[dataIdx]?.age_end?.[0]}岁
                                                </span>
                                            </div>
                                            <Form.Array name={[dataIdx, 'settings']}>
                                                {(fields, { remove, add }) =>
                                                    fields.map(({ index }, idx) => {
                                                        return (
                                                            <>
                                                                <div className={styles.block} id={`data_${dataIdx}_${idx}`}>
                                                                    {!!index && <div className={styles.del_icon} onClick={() => remove(index)} />}
                                                                    <div className={styles.form_item_wrapper}>
                                                                        <div className={styles.form_label}>开始年龄</div>
                                                                        <div className={styles.form_content}>
                                                                            <Form.Subscribe to={[['data', dataIdx, 'settings']]}>
                                                                                {field => {
                                                                                    const { data } = field
                                                                                    const { age_start: role_start, age_end: role_end } = stepData?.[dataIdx] || {}
                                                                                    const curSettings = [...data[dataIdx].settings]
                                                                                    const { age_end } = curSettings[index] || {}
                                                                                    /** 排除当前数据 */
                                                                                    curSettings.splice(index, 1)
                                                                                    /** 获取已经选择过的区间 */
                                                                                    const exclude = curSettings.map((item: any) => {
                                                                                        return [item?.age_start?.[0], item?.age_end?.[0]]
                                                                                    })
                                                                                    /** 排除已选区间 */
                                                                                    let col = ageArr.slice(Number(role_start?.[0]), Number(age_end?.[0] || role_end?.[0]))
                                                                                    col = getRestAge(col, exclude)
                                                                                    /** 没有选项的时候清除数据 */
                                                                                    if (col.length === 0) {
                                                                                        form.resetFields([['data', dataIdx, 'settings', index, 'age_start']])
                                                                                    }
                                                                                    return (
                                                                                        <Form.Item
                                                                                            name={[index, 'age_start']}
                                                                                            rules={[
                                                                                                {
                                                                                                    required: true,
                                                                                                },
                                                                                            ]}
                                                                                            trigger="onConfirm"
                                                                                            noStyle
                                                                                        >
                                                                                            <FormPicker
                                                                                                placeholder="请选择角色开始的年龄"
                                                                                                rightIcon={<img className={styles.arrow} src={arrow_down} />}
                                                                                                columns={[col]}
                                                                                            />
                                                                                        </Form.Item>
                                                                                    )
                                                                                }}
                                                                            </Form.Subscribe>
                                                                        </div>
                                                                    </div>
                                                                    <div className={styles.form_item_wrapper}>
                                                                        <div className={styles.form_label}>结束年龄</div>
                                                                        <div className={styles.form_content}>
                                                                            <Form.Subscribe to={[['data', dataIdx, 'settings']]}>
                                                                                {field => {
                                                                                    const { data } = field
                                                                                    const { age_start: role_start, age_end: role_end } = stepData?.[dataIdx]
                                                                                    const curSettings = [...data[dataIdx].settings]
                                                                                    const { age_start } = curSettings[index] || {}
                                                                                    /** 排除当前数据 */
                                                                                    curSettings.splice(index, 1)
                                                                                    /** 获取已经选择过的区间 */
                                                                                    const exclude = curSettings.map((item: any) => {
                                                                                        return [Number(item?.age_start?.[0]), Number(item?.age_end?.[0])]
                                                                                    })
                                                                                    /** 排除已选区间 */
                                                                                    let col = ageArr.slice(Number(age_start?.[0] || role_start?.[0]) + 1, Number(role_end?.[0]) + 1)
                                                                                    col = getRestAge(col, exclude)
                                                                                    /** 没有选项的时候清除数据 */
                                                                                    if (col.length === 0) {
                                                                                        form.resetFields([['data', dataIdx, 'settings', index, 'age_end']])
                                                                                    }
                                                                                    return (
                                                                                        <Form.Item
                                                                                            name={[index, 'age_end']}
                                                                                            rules={[
                                                                                                {
                                                                                                    required: true,
                                                                                                },
                                                                                            ]}
                                                                                            trigger="onConfirm"
                                                                                            noStyle
                                                                                        >
                                                                                            <FormPicker
                                                                                                placeholder="请选择角色结束的年龄"
                                                                                                rightIcon={<img className={styles.arrow} src={arrow_down} />}
                                                                                                columns={[col]}
                                                                                            />
                                                                                        </Form.Item>
                                                                                    )
                                                                                }}
                                                                            </Form.Subscribe>
                                                                        </div>
                                                                    </div>
                                                                    <div className={styles.form_item_vertical_wrapper}>
                                                                        <div className={styles.form_label}>投入程度</div>
                                                                        <div className={styles.form_content}>
                                                                            <Form.Item
                                                                                name={[index, 'grade']}
                                                                                label="投入程度"
                                                                                rules={[
                                                                                    {
                                                                                        required: true,
                                                                                    },
                                                                                ]}
                                                                                getValueFromEvent={(val: string) => {
                                                                                    return Number(val) < 1 ? '1' : val
                                                                                }}
                                                                                noStyle
                                                                            >
                                                                                <CustomSlider step={1} max={3} ticks />
                                                                            </Form.Item>
                                                                        </div>
                                                                    </div>
                                                                    <div
                                                                        style={{
                                                                            display: errInfo[`${dataIdx}_${index}`] ? 'block' : 'none',
                                                                        }}
                                                                        className={styles.err_info}
                                                                    >
                                                                        请填写完整角色信息
                                                                    </div>
                                                                </div>
                                                                {fields.length - 1 === idx && fields.length < 10 && (
                                                                    <div className={styles.options_wrapper}>
                                                                        <span
                                                                            className={styles.add_wrapper}
                                                                            onClick={() =>
                                                                                add({
                                                                                    grade: 1,
                                                                                })
                                                                            }
                                                                        >
                                                                            <AddCircleOutline />
                                                                            添加年龄段
                                                                        </span>
                                                                    </div>
                                                                )}
                                                            </>
                                                        )
                                                    })
                                                }
                                            </Form.Array>
                                        </div>
                                    </>
                                ))
                            }
                        </Form.Array>
                    </Form>
                </div>
            </BtnBotLayout>
            <GenerateRainbow ref={generateRef} />
        </div>
    )
})
